import random
import urllib
import urllib2
import thread

from Config.RunConfig import RunConfig, Options


class ClientOperations:
    def __init__(self):
        self._operationsList = [
            self._auth,
            self._accountnode,
            self._download,
            self._features,
            self._getservicestatus,
            self._homenode,
            self._storage,
        ]
        self._baseAccount = {
            'account': 'stress123456789',
            'password': '123456789'
        }
        self._token = 'ed751091-35b6-412f-b84e-525d35e7e1f7'
        self._baseStorage = {
            'token': self._token,
            'guid': 'ServerEndpoint'
        }
        self.url = RunConfig().get(Options.Soap.cloudUrl)
        try:
            self._token = self._executeRequest('/auth' + '?' + urllib.urlencode((self._baseAccount)))
            self._baseStorage['token'] = self._token
        except:
            pass

    def _getRandomOperation(self):
        return random.choice(self._operationsList)

    def _executeRequest(self, requestParametr):
        request = urllib2.Request(self.url + requestParametr)
        response = urllib2.urlopen(request)
        return response.read()

    def _auth(self, manserv, partnerId):
        try:
            self._token = self._executeRequest('/auth' + '?' + urllib.urlencode((self._baseAccount)))
        except:
            pass

    def _storage(self, manserv, partnerID):
        self._executeRequest('/storage' + '?' + urllib.urlencode(self._baseStorage))

    def _features(self, manserv, partnerID):
        self._executeRequest('/features' + '?token=' + self._token)

    def _homenode(self, manserv, partnerID):
        self._executeRequest('/homenode' + '?token=' + self._token)

    def _accountnode(self, manserv, partnerID):
        self._executeRequest('/accountnode' + '?token=' + self._token)

    def _getservicestatus(self, manserv, partnerID):
        self._executeRequest('/getservicestatus')

    def _download(self, manserv, partnerID):
        self._executeRequest('/download' + '?' + 'type=eula' + '&' + 'partnerId=' + random.randint(1, 10000))
